package me.firstapp.api.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;

import me.firstapp.api.service.EmailService;
import me.firstapp.common.exception.ServiceException;
import me.firstapp.common.exception.StatusHouse;
import me.firstapp.common.utils.StrUtils;
import me.firstapp.module.system.EmailConfig;
import me.firstapp.service.system.EmailConfigService;

@Service
public class EmailServiceImpl implements EmailService {

	Logger logger = LoggerFactory.getLogger(EmailService.class);

	@Autowired
	private EmailConfigService emailConfigService;

	@Autowired
	private RestTemplate restTemplate;

	@Override
	public void sendEmail(String toEmail, String content, String subject, Long apiClientId) {
		try {
			EmailConfig emailConfig = emailConfigService.findByApiClientIdAndStatus(apiClientId, 1);
			if (emailConfig == null) {
				throw new ServiceException(StatusHouse.EMAIL_CONFIG_NOT_EXIST);
			}
			StringBuilder url = new StringBuilder(emailConfig.getApiUrl());
			url.append("/mail/send");
			url.append("?apiUser=").append(emailConfig.getApiUser());
			url.append("&apiKey=").append(emailConfig.getApiKey());
			url.append("&from=").append(emailConfig.getMailFrom());
			url.append("&to=").append(toEmail);
			url.append("&subject=").append(subject);
			url.append("&html=").append(content);

			ResponseEntity<String> responseEntity = restTemplate.exchange(url.toString(), HttpMethod.POST, null,
					String.class);
			String resultStr = responseEntity.getBody();
			logger.info("发送邮件返回结果==》" + resultStr);
			if (StrUtils.isNotNULL(resultStr)) {
				JSONObject jsonObject = JSONObject.parseObject(resultStr);
				int statusCode = jsonObject.getIntValue("statusCode");
				if (statusCode == 200) {
				} else {
					logger.info("发送邮件失败，失败信息=》" + statusCode + "," + jsonObject.getString("message"));
					throw new ServiceException(statusCode + "", jsonObject.getString("message"));
				}
			}
		} catch (ServiceException e) {
			throw e;
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException(StatusHouse.COMMON_STATUS_ERROR);
		}
	}

}
